package com.xq.jltx.frescosimple.adapters;

import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;

import com.xq.jltx.frescosimple.display.ImageLoadeInstrumented;
import com.xq.jltx.frescosimple.display.PerfListener;

/**
 * @author jltxseo
 *         Created by junlintianxia on 2016年02月02日.
 */

public abstract class ImageListAdapter<V extends  ImageLoadeInstrumented> extends BaseAdapter{
    private PerfListener mPerfListener;
    private String[]  imageList;

    public ImageListAdapter(String[] imageList, PerfListener mPerfListener) {
        this.imageList = imageList;
        this.mPerfListener = mPerfListener;
    }

    @Override
    public int getCount() {
        int count = 0;
        if(imageList != null){
            count = imageList.length;
        }
        return count;
    }

    @Override
    public Object getItem(int i) {
        if(imageList != null && i >= 0 && i < imageList.length){
            return imageList[i];
        }
        return null;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View convertView, ViewGroup viewGroup) {
        View view = convertView;
        final V viewHodler;
        if(convertView == null){
            viewHodler = createViewHolder();
            view = viewHodler.getItemRootView();
            view.setTag(viewHodler);
        }else{
            viewHodler = (V)convertView.getTag();
        }
        AbsListView.LayoutParams ablayoutParams = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        view.setLayoutParams(ablayoutParams);
        String uri = imageList[i];
        viewHodler.initInstrumentation(uri,mPerfListener);
        bind(viewHodler,uri);
        return view;
    }

    private static void updateViewLayoutParams(View view, int width, int height) {
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        if (layoutParams == null || layoutParams.height != width || layoutParams.width != height) {
            layoutParams = new AbsListView.LayoutParams(width, height);
            view.setLayoutParams(layoutParams);
        }
    }

    /** The View subclass used by this adapter's image loader. */
    protected abstract Class<V> getViewClass();

    /** Create a View instance of the correct type. */
    protected abstract V createViewHolder();

    /** Load an image of the specified uri into the view, asynchronously. */
    protected abstract void bind(V viewHolder, String uri);

    /** Releases any resources and tears down the adapter. */
    public abstract void shutDown();
}
